/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.liquidByte.trafficMustang.server.filters;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.liquidByte.trafficMustang.server.services.BusinessContext;
import org.liquidByte.trafficMustang.server.services.PerfilUsuario;

/**
 *
 * @author Alexandre
 */
public class SessionDataBindFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpSession session = httpRequest.getSession(true);
        Integer idUsuario = (Integer)session.getAttribute("user");
        PerfilUsuario perfil = (PerfilUsuario)session.getAttribute("perfil");
        
        if (idUsuario != null) {
            if (perfil != null)  {
                BusinessContext.create(idUsuario, perfil);
            }
            else {
                BusinessContext.create(idUsuario);
            }
        }
        
        chain.doFilter(request, response);
        BusinessContext ctx = BusinessContext.getInstance();
        if (ctx == null) {
            session.setAttribute("user", null);
            session.setAttribute("perfil", null);
        } else {
            session.setAttribute("user", ctx.getIdUsuario());
            session.setAttribute("perfil", ctx.getPerfil());
            
            BusinessContext.destroy();
        }
    }

    public void destroy() {
        
    }
    
}
